package com.juyu.reader.pc.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.juyu.reader.pc.common.PageDirective;
import com.juyu.reader.pc.model.Book;
import com.juyu.reader.pc.model.BookChapter;
import com.juyu.reader.pc.model.Page;
import com.juyu.reader.pc.service.BookChapterService;
import com.juyu.reader.pc.service.SolrService;

@Controller
@RequestMapping("/search")
public class SearchController extends BaseController {
	Logger loger = Logger.getLogger(SearchController.class);
	@Autowired
	private SolrService solrService;
	@Autowired
	private BookChapterService bookChapterService;
	
	/**
	 * 搜索功能(书名、作者、内容)，solr实现
	 * @param request
	 * @param searchBook
	 * @param page
	 * @return
	 */
	@RequestMapping("/index")
	public ModelAndView searchBookList(HttpServletRequest request, Book searchBook, Page page) {
		List<Book> bookList = new ArrayList<Book>();
		try {
			bookList = solrService.searchBook(searchBook.getBookName(), page.getPageNo(), page.getLimit());
		} catch (Exception e) {
			loger.info(e.toString());
		}
		int count = 0;
		if(bookList.size()>0){
			count=bookList.get(0).getSearchBookCount();
		}
		for (Book b : bookList) {
			List<BookChapter> latestChapters = bookChapterService.findBookChapterLatest(b.getBookId());
			if (latestChapters.size() >= 1) {
				b.setBookLatestChapterId(latestChapters.get(0).getChapterId());
				b.setBookLatestChapter(latestChapters.get(0).getChapterName());
			}
		}
		Map<String, Object> attrMap = new HashMap<String, Object>();
		attrMap.put("bookList", bookList);
		attrMap.put("searchBook", searchBook);
		attrMap.put("recordCount", count);
		attrMap.put("page", page);
		attrMap.put("pageftl", new PageDirective(request, page.getLimit()));
		return this.packModeAndView(request, "/book/searchList", null, attrMap);
	}
}
